class Rank < ActiveRecord::Base
  before_save :create_innoaward_rank

  validates :product_id, :award_id, presence: true
  validates_uniqueness_of :product_id, scope: :award_id

  belongs_to :innoaward
  belongs_to :product
  belongs_to :award

  def vote_one ip
    return false if ip_daily_ceiling?(ip)
    update(vote: (self.vote + 1))
    vote
  end

  def ip_daily_ceiling? ip
    key = [id, ip].join('/')
    daily_vote = Rails.cache.fetch(key) do
      0
    end
    bool = daily_vote + 1 >= 10
    Rails.cache.write(key, daily_vote + 1, expires_in: 1.days) unless bool
    bool
  end

  private
  def create_innoaward_rank
    self.innoaward_id = self.award.innoaward_id
  end

  def create_innoaward_product
    InnoawardsProduct.create!(product_id: product.id, innoaward_id: innoaward.id)
  end
end
